//
//  WBHomeViewModel.swift
//  Swift_Weibo
//
//  Created by Tim on 2019/9/6.
//  Copyright © 2019 Tim. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa


/// 允许最多三次上拉刷新接收到 0 条数据
private let maxPullupTryTimes = 3
class WBHomeViewModel {
    
    /// 微博可变数据序列
    let statuses = BehaviorRelay<[WBStatuses]>(value: [])
    
    /// 未读消息数
//    let unreadCount =
    
    
    /// 释放序列池
    private let bag = DisposeBag()
    
    /// 记录当前上拉刷新错误次数，当大于 3 的时候不再进行请求，防止多次上拉刷新造成 api 无法返回数据
    private var pullupErrorTimes = 0
    
    /// 网络获取微博数据
    ///
    /// - Returns: 获取到最新的微博数据数组
    func loadStatuses(isPullUp: Bool) {
        
        if isPullUp && pullupErrorTimes > maxPullupTryTimes{
            return
        }
        
        let sinceId = isPullUp ? 0 : statuses.value.first?.id ?? 0
        let maxId   = !isPullUp ? 0 : statuses.value.last?.id ?? 0
        WBApiProvider.rx.request(.public_status(sinceId: sinceId, maxId: maxId > 0 ? maxId - 1 : 0))
            .asObservable()
            .mapJSON()
            .mapObjects(type: WBStatuses.self, key: "statuses")
            .asDriver(onErrorDriveWith: Driver.empty())
            .drive(onNext:{items in
                debugLog("本次获取到了\(items.count)条微博")
                if isPullUp {
                    if items.count == 0 {
                        self.pullupErrorTimes += 1
                    } else {
                        self.statuses.accept(self.statuses.value + items)
                    }
                } else {
                    self.statuses.accept(items + self.statuses.value)
                }
            })
            .disposed(by: bag)
    }
    
    
    func unreadCount() -> Single<Int> {
        return WBApiProvider.rx.request(.unread_count(uid: uid))
        .asObservable()
        .mapJSON()
        .map({ (json) -> Int in
            guard let jsonDict = json as? [String : Any],
                let unreadCount = jsonDict["status"] as? Int else {
                    return 0
        }
            return unreadCount
        })
        .asSingle()
    }
}
